<template>
  <div>
    <el-row style="margin: 10px">
      <el-col>
        <el-col :span="4" style="margin-left: 20px">
          <el-input v-model="searchTitle" placeholder="通过图片标题搜索" clearable maxlength="10" />
        </el-col>
        <el-col :span="1" style="margin-left: 20px">
          <el-button type="primary" @click="handleSearch">搜索</el-button>
        </el-col>
        <el-col :span="1" style="margin-left: 20px">
          <el-button type="primary" @click="handleAdd()">添加</el-button>
        </el-col>
      </el-col>
    </el-row>
    <el-table :data="listData" style="width: 100%">
      <el-table-column label="标题" align="center">
        <template slot-scope="scope">
          <span style="margin-left: 10px">{{ scope.row.title }}</span>
        </template>
      </el-table-column>
      <el-table-column label="跳转链接" align="center">
        <template slot-scope="scope">
          <span style="margin-left: 10px">{{ scope.row.url }}</span>
        </template>
      </el-table-column>
      <el-table-column label="类型" align="center">
        <template slot-scope="scope">
          <span style="margin-left: 10px">{{ scope.row.type }}</span>
        </template>
      </el-table-column>
      <el-table-column label="反馈图片" align="center">
        <template slot-scope="scope">
          <span v-for="item in scope.row.showImg">
            <el-image :src="item" style="width: 40px; height: 40px; margin: 4px" :preview-src-list="scope.row.showImg" />
          </span>
        </template>
      </el-table-column>
      <el-table-column label="添加时间" width="240px" align="center">
        <template slot-scope="scope">
          <span style="margin-left: 10px"><el-date-picker type="datetime" :value="scope.row.createTime" readonly /></span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template slot-scope="scope">
          <el-button size="mini" type="text" @click="handleEdit(scope.$index, scope.row)">修改</el-button>
          <el-button size="mini" type="text" style="color: #f6416c" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-col :span="12" :offset="14" style="margin-top: 20px">
      <el-pagination
        background
        layout="prev, pager, next, jumper, sizes"
        :current-page="page.currentPage"
        :total="page.total"
        :pager-count="5"
        :page-size="page.pageSize"
        :page-sizes="page.pageSizes"
        @current-change="pageChange"
        @size-change="sizeChange"
      />
    </el-col>
    <el-dialog title="添加图片" :visible.sync="dialogVisible" width="30%" :rules="rules">
      <el-form ref="imgForm" :model="imgForm" :rules="rules" label-width="100px" label-position="right">
        <el-form-item label="标题：" prop="title">
          <el-col :span="18">
            <el-input v-model="imgForm.title" maxlength="20" />
          </el-col>
        </el-form-item>
        <el-form-item label="类型：" prop="type">
          <el-col :span="18">
            <el-select v-model="imgForm.type" style="width: 100%" placeholder="请选择">
              <el-option
                v-for="item in typeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-col>
        </el-form-item>
        <el-form-item label="排序号：" prop="orderNum">
          <el-col :span="18">
            <el-input v-model="imgForm.orderNum" type="number" maxlength="5" />
          </el-col>
        </el-form-item>
        <el-form-item label="跳转地址：" prop="url">
          <el-col :span="18">
            <el-input v-model="imgForm.url" maxlength="50" />
          </el-col>
        </el-form-item>
        <el-form-item label="跳转地址：">
          <el-upload
            action="http://127.0.0.1:9871/file/imgUpload"
            list-type="picture-card"
            accept="image/*"
            :limit="1"
            :file-list="fileLists"
            :multiple="false"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            :on-exceed="handleExceed"
            :on-error="imgUploadError"
          >
            <i class="el-icon-plus" />
          </el-upload>
          <img width="100%" :src="dialogImageUrl" alt="">
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleCancel">取 消</el-button>
        <el-button type="primary" @click="handleConfirm('imgForm')">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog title="编辑" :visible.sync="editDialogVisible" width="30%" :rules="rules">
      <el-form ref="imgForm" :model="imgForm" :rules="rules" label-width="100px" label-position="right">
        <el-form-item label="标题：" prop="title" maxlength="20">
          <el-col :span="18">
            <el-input v-model="imgForm.title" />
          </el-col>
        </el-form-item>
        <el-form-item label="类型：" prop="type">
          <el-col :span="18">
            <el-select v-model="imgForm.type" style="width: 100%" placeholder="请选择">
              <el-option
                v-for="item in typeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-col>
        </el-form-item>
        <el-form-item label="排序号：" prop="orderNum">
          <el-col :span="18">
            <el-input v-model="imgForm.orderNum" type="number" maxlength="5" />
          </el-col>
        </el-form-item>
        <el-form-item label="跳转地址：" prop="url">
          <el-col :span="18">
            <el-input v-model="imgForm.url" maxlength="50" />
          </el-col>
        </el-form-item>
        <span v-for="item in imgForm.showImg">
          <el-image :src="item" :preview-src-list="imgForm.showImg" />
        </span>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleCancel">取 消</el-button>
        <el-button type="primary" @click="handleUpdate('imgForm')">提 交</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getListByPage, addImgModel, updateImgModel, deleteImgModel } from '@/api/imgModel'

export default {
  data() {
    return {
      listData: [],
      searchTitle: '',
      dialogVisible: false,
      editDialogVisible: false,
      dialogImageUrl: '',
      fileLists: [],
      page: {
        pageSize: 5,
        pageSizes: [5, 10, 20, 40, 80],
        totalPage: 1,
        total: 0,
        currentPage: 1
      },
      imgForm: {
        id: '',
        title: '',
        img: '',
        type: '',
        url: '',
        orderNum: 1
      },
      rules: {
        title: [
          { required: true, message: '请输入标题', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        type: [
          { required: true, message: '请输入类型', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        orderNum: [
          { required: true, message: '排序号不能为空' }
        ],
        url: [
          { required: false, message: '请输入图片跳转地址', trigger: 'blur' },
          { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
        ]
      },
      typeOptions: [{
        value: 'h5_index_swiper',
        label: '首页轮播图'
      }]
    }
  },
  computed: {},
  created() {
    this.getList()
  },
  methods: {
    getList() {
      getListByPage({
        page: this.page.currentPage,
        limit: this.page.pageSize,
        searchTitle: this.searchTitle
      }).then((res) => {
        console.log(res)
        this.listData = JSON.parse(res.data.list)
        for (let i = 0; i < this.listData.length; i++) {
          if (this.listData[i].img) {
            this.listData[i].showImg = [].concat(res.data.prefixUrl + this.listData[i].img)
          }
        }
        console.log(this.listData)
        this.page.total = res.data.total
        this.page.totalPage = res.data.totalPage
      })
    },
    handleSearch() {
      this.currentPage = 1
      this.getList()
    },
    pageChange(page) {
      this.page.currentPage = page
      this.getList()
    },
    sizeChange(size) {
      this.page.pageSize = size
      this.getList()
    },
    handleCancel() {
      this.dialogVisible = false
      this.editDialogVisible = false
      this.resetForm()
    },
    handleAdd() {
      this.resetForm()
      this.dialogVisible = true
    },
    handleEdit(index, row) {
      this.imgForm = row
      this.editDialogVisible = true
    },
    handleDelete(index, row) {
      deleteImgModel(row).then((res) => {
        if (res.code === 200) {
          this.$message({
            message: res.message,
            type: 'success'
          })
          this.getList()
          this.resetForm()
        } else {
          this.$message({
            message: res.message,
            type: 'error'
          })
          this.resetForm()
        }
      })
    },
    handleUpdate() {
      updateImgModel(this.imgForm).then((res) => {
        if (res.code === 200) {
          this.$message({
            message: res.message,
            type: 'success'
          })
          this.editDialogVisible = false
          this.getList()
          this.resetForm()
        } else {
          this.$message({
            message: res.message,
            type: 'error'
          })
          this.resetForm()
        }
      })
    },
    handleConfirm(imgForm) {
      if (!this.imgForm.img) {
        this.$message({
          message: '请先上传图片',
          type: 'error'
        })
        return
      }
      this.$refs[imgForm].validate((valid) => {
        if (valid) {
          addImgModel(this.imgForm).then((res) => {
            if (res.data) {
              this.$message({
                message: res.message,
                type: 'success'
              })
              this.getList()
              this.resetForm()
            } else {
              this.$message({
                message: res.message,
                type: 'error'
              })
              this.resetForm()
            }
            this.dialogVisible = false
          })
        } else {
          this.$message({
            message: '格式错误',
            type: 'error'
          })
          return false
        }
      })
    },
    resetForm() {
      this.imgForm.id = ''
      this.imgForm.title = ''
      this.imgForm.img = ''
      this.imgForm.url = ''
      this.imgForm.type = ''
      this.imgForm.orderNum = 1
    },
    // 移除图片
    handleRemove(file, fileList) {
      console.log(file, fileList)
    },
    // 预览图片时调用
    handlePictureCardPreview(file) {
      console.log(file)
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    // 文件上传之前调用做一些拦截限制
    beforeAvatarUpload(file) {
      console.log(file)
      const isJPG = true
      const isLt2M = file.size / 1024 / 1024 < 2

      // if (!isJPG) {
      //   this.$message.error('上传头像图片只能是 JPG 格式!');
      // }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    // 图片上传成功
    handleAvatarSuccess(res, file) {
      console.log(res)
      this.imgForm.img = res.data.url
      this.imageUrl = URL.createObjectURL(file.raw)
    },
    // 图片上传超过数量限制
    handleExceed(files, fileList) {
      this.$message.error('上传图片不能超过1张!')
      console.log(files, fileList)
    },
    // 图片上传失败调用
    imgUploadError(err, file, fileList) {
      console.log(err)
      this.$message.error('上传图片失败!')
    }
  }
}
</script>

<style scoped>

</style>
